package com.longteng.diamond.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import com.longteng.diamond.domain.InterfaceMock;
import com.longteng.diamond.domain.InterfaceMockData;
import com.longteng.diamond.service.MockMatchDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/8/12
 * TIME : 10:13
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Component
@Slf4j
public class JsonPathMatchImpl implements MockMatchDataService {
    /**
     * 通过jsonPath的方法获取mock数据
     *
     * @param
     * @return mockData
     */
    @Override
    public String dataMatch(InterfaceMock interfaceMock, List<InterfaceMockData> interfaceMockDataList, HttpServletRequest httpRequest) {
        /**获取http post 请求的body参数**/
        String paramBody = null;
        try {
            paramBody = IOUtils.toString(httpRequest.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (InterfaceMockData interfaceMockData : interfaceMockDataList) {
            String data = interfaceMockData.getMatchData();
            /**反序列化匹配数据,转换成map类型**/
            Map<String, String> map = JSON.parseObject(data, new TypeReference<HashMap<String, String>>() {
            });
            boolean isMatch = true;
            /**key就是表达式$.name dbValue**/
            for (String key : map.keySet()) {
                String dbValue = map.get(key);
                String paramValue = null;
                try {
                    paramValue = JsonPath.read(paramBody, key);
                } catch (PathNotFoundException p) {
                    log.error("未匹配到正确的规则", p);
                    isMatch=false;
                    break;
                }catch (InvalidPathException i){
                    log.error("jsonPath语法不正确,语法是:{}",key);
                    return "您的jsonPath语法不正确,错误语法是:"+key;
                }
                if (null == paramValue || !dbValue.equalsIgnoreCase(paramValue)) {
                    isMatch = false;
                    break;
                }
            }
            if (isMatch) {
                return interfaceMockData.getMockData();
            }
        }
        return "未匹配到mock数据";
    }
}
